/**
 * 为指定的 maptalks 地图实例添加 GeoJSON 导入功能。
 * @param {maptalks.Map} mapInstance - 要添加功能的地图实例。
 */
function setupGeoJSONImportTool(mapInstance) {
  // --- 1. 参数校验 ---
  if (!mapInstance || typeof mapInstance.addLayer !== "function") {
    console.error(
      "setupGeoJSONImportTool: 传入的参数不是一个有效的 maptalks.Map 实例。"
    );
    return; // 直接退出，不执行后续操作
  }

  // --- DOM 元素 ---
  const importBtn = document.getElementById("import-btn");
  const fileInput = document.getElementById("geojson-file-input");
  const editBtn = document.getElementById("edit-btn");
  const moveBtn = document.getElementById("move-btn");
  const clearBtn = document.getElementById("clear-btn");
  const transBtn = document.getElementById("trans-btn");
  const saveBtn = document.getElementById("save-btn");
  // --- 内部状态 ---
  const importedGeoJsonLayers = [];
  let currentEditingMode = null; // 'edit', 'move', or null
  let activeFeature = null; // 当前正在编辑的 maptalks.Geometry 对象
  let activeLayer = null; // 当前正在被整体移动的 maptalks.VectorLayer 对象
  let geojson = null;

  // --- 工具栏按钮事件 ---
  transBtn.addEventListener("click", onConvertGcj02ToWgs84);
  saveBtn.addEventListener("click", exportGeoJSON);
  importBtn.addEventListener("click", () => fileInput.click());
  editBtn.addEventListener("click", () => setEditingMode("edit"));
  moveBtn.addEventListener("click", () => setEditingMode("move"));
  clearBtn.addEventListener("click", () => onFeatureClear());

  // --- GeoJSON 文件导入逻辑 ---
  fileInput.addEventListener("change", function (event) {
    const file = event.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = function (e) {
      try {
        geojson = JSON.parse(e.target.result);
        // geojson = convertGcj02ToWgs84(geojson);
        if (
          geojson.type &&
          (geojson.type === "FeatureCollection" || geojson.type === "Feature")
        ) {
          // 为每次导入创建一个新的图层，便于管理
          const importedGeoJsonLayer = new maptalks.VectorLayer(
            `imported-geojson-layer-${Date.now()}`
          ).addTo(mapInstance);

          const geometries = maptalks.GeoJSON.toGeometry(geojson);
          importedGeoJsonLayer.addGeometry(geometries);

          importedGeoJsonLayers.push(importedGeoJsonLayer);
          // 定位到新导入的对象，但不改变层级
          if (geometries.length > 0) {
            const extent = geometries[0].getExtent();
            const center = extent.getCenter();
            mapInstance.panTo(center);
          }

          // 导入新数据后，退出任何编辑模式
          setEditingMode("move");
        } else {
          alert("文件格式错误或不是有效的 GeoJSON 文件。");
        }
      } catch (error) {
        console.error("解析 GeoJSON 失败:", error);
        alert("解析 GeoJSON 文件时发生错误。");
      }
    };
    reader.onerror = function () {
      console.error("读取文件失败。");
      alert("读取文件失败。");
    };
    reader.readAsText(file);
    event.target.value = ""; // 清空input值，允许重复导入同一文件
  });

  // --- 编辑功能核心逻辑 ---

  /**
   * 设置当前的编辑模式，并更新UI和要素样式
   * @param {string|null} mode - 'edit', 'move', or null
   */
  function setEditingMode(mode) {
    // 如果点击的是已激活的按钮，则关闭该模式
    if (currentEditingMode === mode) {
      mode = null;
    }

    // 清理上一个激活的要素或图层的状态
    if (activeFeature) {
      onActiveFeatureClear();
    }

    // 如果当前有图层被选中进行移动，先取消选中
    if (activeLayer) {
      deselectLayer();
    }

    currentEditingMode = mode;
    // 更新按钮UI状态
    editBtn.classList.toggle("active", mode === "edit");
    moveBtn.classList.toggle("active", mode === "move");

    // 根据模式更新地图交互状态
    if (mode) {
      mapInstance.config("draggable", false); // 禁用地图拖动
      mapInstance.getContainer().style.cursor =
        mode === "move" ? "move" : "grab";
    } else {
      mapInstance.config("draggable", true); // 启用地图拖动
      mapInstance.getContainer().style.cursor = "";
    }
  }

  // 地图点击事件：用于选择要编辑的要素或图层
  mapInstance.on("click", function (event) {
    if (!currentEditingMode) {
      return;
    }
    if (activeFeature) {
      onActiveFeatureClear();
    }
    mapInstance.identify(
      {
        coordinate: event.coordinate,
        layers: importedGeoJsonLayers, // 只在我们导入的图层中识别
        count: 1, // 只取最顶层的第一个要素
      },
      function (geos) {
        if (geos && geos.length > 0) {
          activeFeature = geos[0];
          if (currentEditingMode === "move") {
            // 移动模式：选中要素所在的整个图层
            selectLayer(activeFeature);
          } else if (currentEditingMode === "edit") {
            // 编辑模式：高亮并开始编辑单个要素
            activeFeature.updateSymbol({
              lineColor: "#ff0000", // 线条颜色变红表示高亮
            });
            activeFeature.on("dragstart dragend", onFeatureDragStartEnd);
            activeFeature.startEdit();
          }
        } else {
          // 如果点击了空白处
          if (currentEditingMode === "move") {
            // 移动模式下，点击空白处取消图层选中
            deselectLayer();
          }
        }
      }
    );
  });

  function selectLayer(feature) {
    // 如果已有选中的图层，先取消选中
    if (activeLayer) {
      deselectLayer();
    }

    // 获取当前要素所在的图层
    activeLayer = feature.getLayer();
    if (!activeLayer) return;

    // 提供视觉反馈：为图层内所有要素添加一个醒目的外框
    activeLayer.forEach((geom) => {
      geom.updateSymbol({
        lineColor: "#ff0000", // 使用红色边框表示图层被选中
      });
    });

    // 保存原始位置和所有几何要素的坐标
    let startCoord = null;
    const originalCoords = {};
    activeLayer.getGeometries().forEach((geom, index) => {
      originalCoords[index] = geom.getCoordinates();
    });

    // 监听地图事件（而不是图层事件）
    const moveHandler = function (e) {
      // 检查是否点击/拖动的是当前图层
      mapInstance.identify(
        {
          coordinate: e.coordinate,
          layers: [activeLayer],
        },
        (identified) => {
          // 只有在点击/拖动当前图层时才执行移动操作
          if (e.type === "mousedown") {
            if (!identified || identified.length === 0) return;
            startCoord = e.coordinate;
          } else if (e.type === "mousemove" && startCoord) {
            const currentCoord = new maptalks.Coordinate(e.coordinate);
            const offset = currentCoord.substract(startCoord);
            activeLayer.getGeometries().forEach((geom, index) => {
              const original = originalCoords[index];
              // 处理不同类型的几何要素
              if (Array.isArray(original)) {
                // 递归处理嵌套坐标数组
                const processCoords = (coords) => {
                  if (Array.isArray(coords)) {
                    return coords.map(processCoords);
                  } else if (coords instanceof maptalks.Coordinate) {
                    // 保持Coordinate对象格式
                    return new maptalks.Coordinate(
                      coords.x + offset.x,
                      coords.y + offset.y
                    );
                  } else {
                    // 处理普通数组坐标
                    const c = new maptalks.Coordinate(coords[0], coords[1]);
                    return new maptalks.Coordinate(
                      c.x + offset.x,
                      c.y + offset.y
                    );
                  }
                };
                const newCoords = processCoords(original);
                geom.setCoordinates(newCoords);
              } else if (original && original.x !== undefined) {
                // 处理点要素
                const newCoord = new maptalks.Coordinate(
                  original.x + offset.x,
                  original.y + offset.y
                );
                geom.setCoordinates(newCoord);
              }
            });
          } else if (e.type === "mouseup") {
            // 更新原始坐标
            activeLayer.getGeometries().forEach((geom, index) => {
              originalCoords[index] = geom.getCoordinates();
            });
            startCoord = null;
          }
        }
      );
    };

    // 添加事件监听
    mapInstance.on("mousedown", moveHandler);
    mapInstance.on("mousemove", moveHandler);
    mapInstance.on("mouseup", moveHandler);

    // 保存事件处理器以便后续移除
    activeLayer._moveHandler = moveHandler;
  }

  function deselectLayer() {
    if (!activeLayer) return;

    // 恢复图层内所有要素的原始样式
    activeLayer.forEach((geom) => {
      geom.updateSymbol({
        lineColor: "#000", // 恢复黑色边框
      });
    });

    // 移除事件监听
    if (activeLayer._moveHandler) {
      mapInstance.off("mousedown", activeLayer._moveHandler);
      mapInstance.off("mousemove", activeLayer._moveHandler);
      mapInstance.off("mouseup", activeLayer._moveHandler);
      delete activeLayer._moveHandler;
    }

    activeLayer = null;
  }

  // 事件处理函数：在要素拖拽开始/结束时切换地图的拖拽状态
  function onFeatureDragStartEnd(param) {
    if (param.type === "dragstart") {
      mapInstance.config("draggable", false);
    } else {
      mapInstance.config("draggable", true);
    }
  }

  /**
   * 清除当前激活的要素功能
   * 该函数用于重置要素的样式并清除相关事件监听
   */
  function onActiveFeatureClear() {
    activeFeature.updateSymbol({ lineColor: "#000" }); // 恢复线条颜色为默认黑色
    activeFeature.off("dragstart dragend", onFeatureDragStartEnd); // 移除要素拖拽开始和结束的事件监听
    activeFeature.endEdit(); // 结束要素的编辑状态
    activeFeature = null; // 将当前激活的要素引用置空
  }

  // 事件处理函数：清除所有导入的图层
  function onFeatureClear() {
    if (!importedGeoJsonLayers.length) return;
    importedGeoJsonLayers.forEach((layer) => {
      mapInstance.removeLayer(layer);
    });
    importedGeoJsonLayers.length = 0; // 清空数组引用
    setEditingMode(null); // 清除所有编辑状态
    console.log("所有导入的GeoJSON图层已被清除。");
  }

  function onConvertGcj02ToWgs84() {
    const json = convertGcj02ToWgs84(geojson);
    if (!json) {
      alert("请先导入对象");
      return;
    }
    _saveFile(json);
  }

  function _saveFile(json) {
    // 将json字符串保存到本地
    const blob = new Blob([JSON.stringify(json)], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "export.geojson";
    a.click();
    URL.revokeObjectURL(url);
  }

  // 将图层导出为geojson
  function exportGeoJSON() {
    let layers = [];
    if (importedGeoJsonLayers.length) {
      layers = importedGeoJsonLayers;
    } else {
      const layer = setupDrawTool.prototype._getLayers();
      if (!layer) return;
      debugger;
      layers = [layer];
    }
    // 遍历所有图层，将其转换为GeoJSON格式
    layers.forEach((layer) => {
      const geometries = layer.getGeometries();
      const features = geometries.map((geom) => geom.toGeoJSON());
      const geojson = {
        type: "FeatureCollection",
        features: features,
      };
      _saveFile(geojson);
    });
  }

  // (可选) 返回一个控制对象，提供从外部操作此功能的能力，例如销毁
  return {
    getLayers: () => importedGeoJsonLayers,
    convertGcj02ToWgs84: () => {
      return convertGcj02ToWgs84(geojson);
    },
    destroy: () => {
      // 移除事件监听器
      // 注意：在实际项目中，最好将事件处理函数定义为命名函数并保存引用，以便精确移除。
      // 这里为了简洁，使用一个简化的方式。
      importBtn.removeEventListener("click", () => fileInput.click());
      // fileInput的监听器需要保存其引用才能移除，这里省略

      // 从地图上移除所有图层
      onFeatureClear();

      // 移除地图事件监听
      mapInstance.off("click");

      console.log(
        `GeoJSON import tool for map ${mapInstance.id} has been destroyed.`
      );
    },
  };
}

function setupDrawTool(mapInstance) {
  const selectedFeature = [];
  let currentEditingMode = null;
  let drawTool;
  const drawLayer = new maptalks.VectorLayer("draw-layer").addTo(mapInstance);
  // --- DOM 元素 ---
  const polygonBtn = document.getElementById("polygon-btn");
  const lineBtn = document.getElementById("line-btn");
  const pointBtn = document.getElementById("point-btn");
  const circleBtn = document.getElementById("circle-btn");
  const rectangleBtn = document.getElementById("rectangle-btn");
  const removeBtn = document.getElementById("remove-btn");
  const cursorBtn = document.getElementById("cursor-btn");

  polygonBtn.addEventListener("click", () => setEditingMode("Polygon"));
  lineBtn.addEventListener("click", () => setEditingMode("LineString"));
  pointBtn.addEventListener("click", () => setEditingMode("Point"));
  circleBtn.addEventListener("click", () => setEditingMode("Circle"));
  rectangleBtn.addEventListener("click", () => setEditingMode("Rectangle"));
  removeBtn.addEventListener("click", () => removeDraw());
  cursorBtn.addEventListener("click", () => selectPoint());
  // 鼠标右键结束绘制
  mapInstance.on("contextmenu", function (event) {
    drawTool.endDraw();
    drawTool.disable();
  });

  setup();

  function setup() {
    // 初始化绘制工具
    drawTool = new maptalks.DrawTool({
      mode: "Polygon",
      once: true,
    }).addTo(mapInstance);
    drawTool.disable();
    // 绘制完成事件
    drawTool.on("drawend", function (param) {
      if (currentEditingMode === null) {
        return;
      }
      const geometry = param.geometry;
      geometry.addTo(drawLayer);
    });

    onSelect();
  }

  function setEditingMode(mode) {
    // 如果点击的是已激活的按钮，则关闭该模式
    if (currentEditingMode === mode) {
      mode = null;
    }
    currentEditingMode = mode;
    // 更新按钮UI状态
    polygonBtn.classList.toggle("active", mode === "Polygon");
    lineBtn.classList.toggle("active", mode === "LineString");
    pointBtn.classList.toggle("active", mode === "Point");
    circleBtn.classList.toggle("active", mode === "Circle");
    rectangleBtn.classList.toggle("active", mode === "Rectangle");

    // 根据模式更新地图交互状态
    if (mode) {
      drawTool.setMode(mode).enable();
      mapInstance.getContainer().style.cursor =
        mode === "Point" ? "crosshair" : "grab";
    } else {
      drawTool.endDraw();
      mapInstance.getContainer().style.cursor = "";
    }
  }

  function removeDraw() {
    unSelectedBtn();
    if (selectedFeature.length > 0) {
      selectedFeature.forEach((f) => {
        f.remove();
      });
    } else if (drawLayer) {
      drawLayer.clear();
    }
  }

  function unSelectedBtn() {
    drawTool.endDraw();
    currentEditingMode = null;
    polygonBtn.classList.toggle("active", false);
    lineBtn.classList.toggle("active", false);
    pointBtn.classList.toggle("active", false);
    circleBtn.classList.toggle("active", false);
    rectangleBtn.classList.toggle("active", false);
  }

  function onSelect() {
    mapInstance.on("click", function (event) {
      if (!drawLayer) {
        return;
      }
      mapInstance.identify(
        {
          coordinate: event.coordinate,
          layers: [drawLayer], // 只在我们导入的图层中识别
        },
        function (geos) {
          if (geos && geos.length > 0) {
            const feature = geos[0];
            // 编辑模式：高亮并开始编辑单个要素
            feature.updateSymbol({
              lineColor: "#ff0000", // 线条颜色变红表示高亮
            });
            endEditAll();
            selectedFeature.length = 0;
            unSelectedBtn();
            feature.startEdit();
            selectedFeature.push(feature);
          } else {
            // 重新开始绘制
            if (currentEditingMode) {
              drawTool.enable();
            }
          }
        }
      );
    });
  }

  // 清空绘制状态
  function selectPoint() {
    // 清空绘制状态
    unSelectedBtn();
    endEditAll();
  }

  function endEditAll() {
    selectedFeature.forEach((f) => {
      f.updateSymbol({
        lineColor: "#000", // 线条颜色变黑表示取消高亮
      });
      f.endEdit();
    });
  }
}

setupDrawTool.prototype._getLayers = function () {
  const layer = map.getLayers().find((layer) => layer.getId() === "draw-layer");
  return layer;
};
